<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Functors (Function Objects)</title>
  <meta
 content="C++ Tutorial: Functors (Function Objects)"
 name="description" />
  <meta
 content="C++ Tutorial, Functors (Function Objects)"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">
<br />
<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>


<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial -   Functors (Function Objects)</span></div>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>


<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>

<br /><br />
<img src="images/functors/KangWhaDo.png" alt="KangWhaDo"/>
<br /><br />


<div class="bodytext" style="padding: 12px;" align="justify">
<div class="subtitle" id="friendfunctions">Functors (Function Objects) </div>
<p>Functors (Function Objects or Functionals) are simply put <strong>object + ()</strong>. In other words, a functor is any object that can be used with <strong>()</strong> in the manner of a function. </p>
<p>This includes normal functions, pointers to functions, and class objects for which the <strong>() operator</strong> (function call operator) is overloaded, i.e., classes for which the function <strong>operator()()</strong> is defined.</strong></p>
<p>Sometimes we can use a function object when an ordinary function won't work. The STL often uses function objects and provides several function objects that are very helpful.</p>
<p>Function objects are another example of the power of generic programming and the concept of pure abstraction. We could say that anything that behaves like a function is a function. So, if we define an object that behaves as a function, it can be used as a function.</p>
<p>For example, we could defin a struct names <strong>absValue</strong> that encapsulates the operation of converting a value of type <strong>float</strong> to its absolute valie:</p>
<pre>
#include &lt;iostream&gt;

struct absValue
{
	float operator()(float f) {
		return f > 0 ? f : -f;
	}
};

int main( ) 
{ 
	using namespace std;

	float f = -123.45;
	<font color="red">absValue aObj;</font>
	float abs_f = <font color="red">aObj(f);</font>
	cout << "f = " << f << " abs_f = " << abs_f << endl;
	return 0; 
}
</pre>
<p>Output is:</p>
<pre>
f = -123.45 abs_f = 123.45
</pre>
<p>As we see from the definition, even though <strong>aObj</strong> is an object and not a function, we were able to make a call on that object. The effect is to run the overloaded call operator defined by the object <strong>absValue</strong>. Tha operator takes a <strong>float</strong> value and returns its absolute value. Note that the function-call operator must be declared as a member function. </p>
<p>So, Objects of class types, like the <strong>absValue</strong> object, that define the call operator are referred to as <strong>function object</strong>.</p>

<p>Let's look at another example simulating a line. The class object is working as a functor taking <strong>x</strong> for a given y-intercept(b) and slope(a) giving us the corresponding <strong>y</strong> coordinate.</p>
<pre>
	y = ax + b
</pre>
<p>Here is the code:</p>
<pre>
#include &lt;iostream&gt;
using namespace std;

class Line {
	double a;	// slope
	double b;	// y-intercept

public:
	Line(double slope = 1, double yintercept = 1):
		a(slope),b(yintercept){} 
	double operator()(double x){
		return a*x + b;
	}
};

int main () {
	Line fa;			// y = 1*x + 1
	Line fb(5.0,10.0);		// y = 5*x + 10

	double y1 = fa(20.0);		// y1 = 20 + 1
	double y2 = fb(3.0);		// y2 = 5*3 + 10

	cout << "y1 = " << y1 << " y2 = " << y2 << endl;
	return 0;
}
</pre>
<p>Here <strong>y1</strong> is calculated using the expression <strong>1 * 20 + 1</strong> and <strong>y2</strong> is calculated using the expression <strong>5 * 3 + 10</strong>. In the expression <strong>a *x + b</strong>, the values for <strong>b</strong> and <strong>a</strong> come from the constructor for the object, and the value of <strong>x</strong> comes from the argument to <strong>operator()</strong>().</p>
<p>Now that we have a little bit of taste for functor, let's step back and think. So, what's the behavior of a function? A functional behavior is something that we can call by using parentheses and passing arguments. For example:</p>
<pre>
	func(arg1, arg2);
</pre>
<p>If we want objects to behave this way, we have to make it possible to <strong>call</strong> them by using <strong>parentheses</strong> and <strong>passing arguments</strong>. It's not that difficult. All we have to do is to define <strong>operator ()</strong> with the appropriate parameter types:</p>
<pre>
Class X {
public:
	// define "function call" operator
	return-value operator() (arguments) const;
	...
};
</pre>
<p>Then we can use object of this class to behave as a function that we can call:</p>
<pre>
X fn;
...
fn(arg1, arg2);	// call operator () for function object fn
</pre>
<p>This call is equivalent to:
<pre>
fn.operator()(arg1,arg2);	// call operator () for function object fn
</pre>
<p>Here is a function object example.</p>
<pre>
#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;algorithm&gt;
using namespace std;

class Print {
public:
	void operator()(int elem) const {
		cout << elem << " ";
	}
};

int main () {
	vector<int> vect;
	for (int i=1; i<10; ++i) {
		vect.push_back(i);
	}

	Print print_it;
	for_each (vect.begin(), vect.end(), print_it);
	cout << endl;
	return 0;
}
</pre> 
<p>The <strong>for_each</strong> function applied a specific function to each member of a range:</p>
<pre>
	for_each (vect.begin(), vect.end(), print_it);
</pre>
<p>In general, the 3rd argument could be a functor, not just a regular function. Actually, this raises a question. <strong>How do we declare the third argument?</strong> We can't declare it as a function pointer because a function pointer specifies the argument type. Because a container can contain just about any type, we don't know in advance what particular type should be used. The STL solves that problem by using <strong>template</strong>.</p>
<p>The class <strong>Print</strong> defines object for which we can call <strong>operator ()</strong> with an <strong>int</strong> argument. The expression<br />
<pre>
print_it
</pre>
in the statement <br />
<pre>
for_each (vect.begin(), vect.end(), print_it);
</pre>
creates a temporary object of this class, which is passed to the <strong>for_each()</strong> algorithm as an argument. The <strong>for_each</strong> algorithm looks like this:<br />
<pre>
template&lt;class Iterator, class Function&gt;
Function for_each(Iterator first, Iterator last, Function f) {
	while (first != end) {
		f(*first);	
		++first;
	}
	return f;
}
</pre>
<strong>for_each</strong> uses the temporary function <strong>f</strong> to call <strong>f(*first)</strong> for each element <strong>first</strong>. If the third parameter is an ordinary function, it simply call it with <strong>*first</strong> as an argument. If the third parameter is a function object, it calls <strong>operator()</strong> for the function object <strong>f</strong> with <strong>*first</strong> as an argument. Thus, in this example <strong>for_each()</strong> calls:<br />
<pre>
print_it::operator()(*first)
</pre>
The out is:<br />
<pre>
1 2 3 4 5 6 7 8 9
</pre>
<p>Here are some advantages of function object listed in "The C++ Standard Library" by Nicolai M. Josuttis.</p>
<ol>
	<li>Function object are "smart functions." <br />
	Objects that behave like pointers are smart pointers. This is similarly true for objects that behave like functions: They can be "smart functions" because they may have abilities beyond operator (). Function objects may have other member functions and attributes. This means that function objects have a state. 
.... </li>
	<li>Each function object has its own type. <br />
	Ordinary functions have different types only when their signatures differ. However, function objects can have different types when their signatures are the same. In fact, each functional behavior defined by a function object has its own type. This is a significant improvement for generic programming using templates because you can pass functional behavior as a template parameter.
...
</li>
	<li>Function objects are usually faster than ordinary functions. <br />
The concept of templates usually allows better optimization because more details are defined at compile time. Thus, passing function objects instead of ordinary functions often results in better performance.</li>
</ol>


<br /><br />
<div class="subtitle_2nd" id="Predicates">Predicates</div>
<p>STL refines <strong>functor</strong> concepts as follows:</p>
<ul>
	<li>A <strong>generator</strong> is a functor that can be called with no argument.</li>
	<li>A <strong>unary function</strong> is a functor that can be called with one argument.</li>
	<li>A <strong>binary function</strong> is a functor that can be called with two arguments.</li>
</ul> 
<p>The <strong>print_it</strong> functor for <strong>for_each()</strong> we used in the previous section is a <strong>unary function</strong> because it is applied to one container element at a time.</p>
<p>A special auxiliary function for algorithm is a <strong>predicate</strong>. Predicates are functions that return a <strong>Boolean</strong> value (or something that can be implicitly converted to <strong>bool</strong>). In other words, a <strong>predicate class</strong> is a functor class whose <strong>operator()</strong> function is a predicate, i.e., its <strong>operator()</strong> returns <strong>true</strong> or <strong>false</strong>.</p>
<p><strong>Predicates</strong> are widely used in the STL. The comparison functions for the standard associative containers are predicates, and predicate functions are commonly passed as parameters to algorithms like <strong>find_if</strong>. Depending on their purpose, predicates are unary or binary.</p>
<ul>
	<li>A <strong>unary function</strong> that returns a <strong>bool</strong> value is a <strong>predicate</strong>.</li>
	<li>A <strong>binary function</strong> that returns a <strong>bool</strong> value is a <strong>binary predicate</strong>.</li>

</ul>


<br /><br />
<img src="images/functors/PyungChang.png" alt="PyungChang"/>
<br /><br />



<br /><br />
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
<br /><br />


<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
